package com.pucong.gitee.database.backup.database.service;

import com.pucong.gitee.database.backup.common.entity.BackupDatabase;
import com.pucong.gitee.database.backup.configuration.exception.BusinessException;
import com.pucong.gitee.database.backup.database.mapper.BackupDatabaseMapper;
import com.pucong.gitee.database.backup.database.mapper.BackupExeSqlLogMapper;
import com.pucong.gitee.database.backup.database.util.BackupService;
import com.pucong.gitee.database.backup.database.util.BackupServiceFactory;
import com.pucong.gitee.database.backup.utils.UUID;
import com.pucong.gitee.database.backup.utils.jdbcPool.JdbcConnectionManager;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Service
public class DatabaseStaticServiceImpl implements DatabaseStaticService {

    @Autowired
    private BackupDatabaseMapper backupDatabaseMapper;

    @Autowired
    private BackupExeSqlLogMapper backupExeSqlLogMapper;

    @Override
    public BackupService getConnectionById(String sessionId,String databaseId){
        if(StringUtils.isBlank(sessionId)){
            sessionId = databaseId + "_" + UUID.uuid();
        }
        BackupDatabase backupDatabase = backupDatabaseMapper.selectById(databaseId);
        if(backupDatabase == null){
            throw new BusinessException("获取数据库异常，未找到数据");
        }
        BackupServiceFactory backupServiceFactory = new BackupServiceFactory();
        BackupService backupService = backupServiceFactory.getBackupService(backupDatabase, backupExeSqlLogMapper);
        backupService.setSessionId(sessionId);
        Boolean connection = backupService.getConnection();
        if(!connection){
            throw new BusinessException("数据库连接失败");
        }
        return backupService;
    }
}
